package com.leyou.gateway.logFilter;

import com.leyou.auth.constants.JwtConstants;
import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Slf4j
@Component
public class loginFliter implements GlobalFilter, Ordered {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取request对象
        ServerHttpRequest request = exchange.getRequest();
        //获取cookie
        HttpCookie cookie = request.getCookies().getFirst(JwtConstants.COOKIE_NAME);
        //判断是否登陆,没有登陆则放行
        if(cookie==null){
            log.info("用户没有登陆");
            return chain.filter(exchange);
        }
        try {
            //校验token是否有效
            String tocken = cookie.getValue();
            //解析token
            Payload payload = jwtUtils.parseJwt(tocken);
            UserDetail userDetail = payload.getUserDetail();
            //刷新有效jwt有效时间
            jwtUtils.refreshJwt(userDetail.getId());
            log.info("用户{}正在访问{}", userDetail.getUsername(), request.getURI().getPath());
        } catch (Exception e) {
           log.info("用户信息无效");
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
     // 登录拦截，可以采用最高优先级！
        return HIGHEST_PRECEDENCE;
    }
}
